package com.zhr.handler;

import com.zhr.digit.FindExpression;
import com.zhr.server.WeixinRequest;
import com.zhr.server.WeixinResponse;
import com.zhr.type.MsgType;

public class MessageCalcHandler extends MessageAbstractHandler {

	@Override
	public WeixinResponse handle(WeixinRequest request) {
		WeixinResponse response = super.handle(request);
		response.setFuncFlag("1");
		response.setMsgType(MsgType.text.name());
		response.setContent(calcResponse(request.getContent()));
		return response;
	}

	@Override
	public int getPriority() {
		return NORM_PRIORITY;
	}

	private String calcResponse(String requestContent) {
		String digitStrs[] = requestContent.split("[ ,]+");
		if (digitStrs.length < 3) {
			return "参数太少无法计算";
		}
		int result = Integer.parseInt(digitStrs[0]);
		int digits[] = new int[digitStrs.length - 1];
		for (int i = 1; i < digitStrs.length; i++) {
			digits[i - 1] = Integer.parseInt(digitStrs[i]);
		}
		FindExpression findExpression = new FindExpression(result, digits);
		if (findExpression._find()) {
			System.out.println(findExpression.getSteps());
			return "算出来啦，结果是 :" + findExpression.getStepResult();
		}
		return "我也算不出来额。。。";
	}

	@Override
	public boolean accpet(WeixinRequest request) {
		String digitStrs[] = request.getContent().split("[ ,]+");
		if (digitStrs.length >= 3) {
			try {
				for (String string : digitStrs) {
					Integer.parseInt(string);
				}
			} catch (Exception e) {
				return false;
			}
			return true;
		}
		return false;
	}

}
